package com.usian.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.usian.mapper.*;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.service.ItemService;
import com.usian.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemCatMapper tbItemCatMapper;
    @Autowired
    private TbItemParamMapper itemParamMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Autowired
    private TbItemParamItemMapper tbItemParamItemMapper;

    /*缓存redis*/
    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    @Value("${ITEM_INFO}")
    private String ITEM_INFO;

    @Value("${BASE}")
    private String BASE;

    @Value("${DESC}")
    private String DESC;

    @Value("${PARAM}")
    private String PARAM;

    @Value("${ITEM_INFO_EXPIRE}")
    private Integer ITEM_INFO_EXPIRE;

    @Autowired
    private RedisClient redisClient;


    /*查询商品类目接口*/
    @Override
    public TbItem selectItemInfo(Long itemId) {
        //查询缓存
        TbItem tbItem1 = (TbItem) redisClient.get(ITEM_INFO + ":" + itemId + ":"+ BASE);
        if(tbItem1 != null){
            return tbItem1;
        }

        TbItem tbItem = tbItemMapper.selectByPrimaryKey(itemId);
        //把数据保存到缓存
        redisClient.set(ITEM_INFO + ":" + itemId + ":"+ BASE,tbItem);
        //设置缓存的有效期
        redisClient.expire(ITEM_INFO + ":" + itemId + ":"+ BASE,ITEM_INFO_EXPIRE);
        return tbItem;
    }
    /*查询商品列表接口*/
    @Override
    public PageResult selectTbItemAllByPage(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        //构建查询
        TbItemExample tbItemExample=new TbItemExample();
        TbItemExample.Criteria criteria = tbItemExample.createCriteria();
        criteria.andStatusEqualTo((byte)1);
        List<TbItem> list=tbItemMapper.selectByExample(tbItemExample);

        PageInfo<TbItem> pageinfo=new PageInfo<>(list);

        PageResult p=new PageResult();
        p.setPageIndex(pageinfo.getPageNum());
        p.setTotalPage(pageinfo.getPages());
        p.setResult(pageinfo.getList());
        return p;
    }

    /*
     *   根据查询商品类目接口
     * */
    @Override
    public  List<TbItemCat> selectItemCategoryByParentId(Integer id) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo((long)id);
        criteria.andStatusEqualTo(1);
        List<TbItemCat> list = this.tbItemCatMapper.selectByExample(example);
        return list;

    }



    /**
     * 根据类目 ID 查询当前类目的子节点
     */
    @Override
    public TbItemParam selectItemParamByItemCatId(long itemCatId) {
        TbItemParamExample example=new TbItemParamExample();
        TbItemParamExample.Criteria criteria = example.createCriteria();
        criteria.andIdGreaterThanOrEqualTo(itemCatId);

        List<TbItemParam> list=itemParamMapper.selectByExampleWithBLOBs(example);
        if (list.size()>0) {
            return list.get(0);
        }
        return null;
    }


    @Override
    public Integer insertTbItem(TbItem tbItem, String desc, String itemParams) {
        //补齐tbitem数据
        Long  l = IDUtils.genItemId();
        Date date = new Date();
        tbItem.setId(l);
        tbItem.setStatus((byte)1);
        tbItem.setUpdated(date);
        tbItem.setCreated(date);
        tbItem.setPrice(tbItem.getPrice());
        Integer i = tbItemMapper.insertSelective(tbItem);

        //补齐商品描述对象
        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(l);
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setCreated(date);
        tbItemDesc.setUpdated(date);
        Integer tbitemDescNum = tbItemDescMapper.insertSelective(tbItemDesc);

        //补齐商品规格参数
        TbItemParamItem tbItemParamItem = new TbItemParamItem();
        tbItemParamItem.setItemId(l);
        tbItemParamItem.setParamData(itemParams);
        tbItemParamItem.setUpdated(date);
        tbItemParamItem.setCreated(date);
        Integer itemParamItmeNum =
                tbItemParamItemMapper.insertSelective(tbItemParamItem);

        return i + tbitemDescNum + itemParamItmeNum;
    }




    @Override
    public Integer deleteItemById(Long itemId) {
       //item_param_item
        TbItemParamItemExample example=new TbItemParamItemExample();
        TbItemParamItemExample.Criteria criteria = example.createCriteria();
        criteria.andItemIdEqualTo(itemId);
        int num=tbItemParamItemMapper.deleteByExample(example);

        //itme_desc
        int num1 = tbItemDescMapper.deleteByPrimaryKey(itemId);

        //item
        TbItem tbItem=new TbItem();
        tbItem.setStatus((byte)3);
        tbItem.setId(itemId);
        int num2 = tbItemMapper.updateByPrimaryKeySelective(tbItem);

       return num+num1+num2;

    }


    /**
     * 根据商品 ID 查询商品，商品分类，商品描述，商品规格参数
     * @param itemId
     * @return
     */
    @Override
    public Map<String, Object> preUpdateItem(String itemId) {
        Map<String,Object> map=new HashMap<>();
        TbItem item = this.tbItemMapper.selectByPrimaryKey(Long.parseLong(itemId));
        map.put("item",item);
        //根据商品 ID 查询商品描述
        TbItemDesc itemDesc = this.tbItemDescMapper.selectByPrimaryKey(Long.parseLong(itemId));
        map.put("itemDesc", itemDesc.getItemDesc());
        //根据商品 ID 查询商品类目
        TbItemCat itemCat = this.tbItemCatMapper.selectByPrimaryKey(item.getCid());
        map.put("itemCat", itemCat.getName());
        //根据商品 ID 查询商品规格信息
        TbItemParamItemExample example = new TbItemParamItemExample();
        TbItemParamItemExample.Criteria criteria = example.createCriteria();
        criteria.andItemIdEqualTo(Long.parseLong(itemId));
        List<TbItemParamItem> list =
                this.tbItemParamItemMapper.selectByExampleWithBLOBs(example);
        if (list != null && list.size() > 0) {
            map.put("itemParamItem", list.get(0).getParamData());
        }
        return map;
    }

    @Override
    public Integer updateTbItem(TbItem tbItem, String desc, String itemParams){
        tbItem.setUpdated(new Date());
        int i = tbItemMapper.updateByPrimaryKeySelective(tbItem);

        //修改描述
        TbItemDesc tbItemDesc=new TbItemDesc();
        tbItemDesc.setUpdated(new Date());
        tbItemDesc.setItemId(tbItem.getId());
        tbItemDesc.setItemDesc(desc);
        int i1 = tbItemDescMapper.updateByPrimaryKeySelective(tbItemDesc);

        //修改规格参数
        TbItemParamItem tbItemParamItem=new TbItemParamItem();
        tbItemParamItem.setItemId(tbItem.getId());
        tbItemParamItem.setParamData(itemParams);
        TbItemParamItemExample tbItemParamItemExample=new TbItemParamItemExample();
        TbItemParamItemExample.Criteria criteria = tbItemParamItemExample.createCriteria();
        criteria.andItemIdEqualTo(tbItem.getId());
        List<TbItemParamItem> tbItemParamItems = tbItemParamItemMapper.selectByExampleWithBLOBs(tbItemParamItemExample);
        tbItemParamItem.setId(tbItemParamItems.get(0).getId());
        int i2 = tbItemParamItemMapper.updateByPrimaryKeyWithBLOBs(tbItemParamItem);

        return i+i1+i2;
    }

    @Override
    public PageResult selectItemParamAll(Integer page, Integer rows) {
        PageHelper.startPage (page,rows);
        TbItemParamExample example = new TbItemParamExample();
        example.setOrderByClause("updated DESC");
        List<TbItemParam> list = this.itemParamMapper.selectByExampleWithBLOBs(example);
        PageInfo<TbItemParam> pageInfo = new PageInfo<>(list);
        PageResult pageResult = new PageResult();
        pageResult.setPageIndex(page);
        pageResult.setResult(pageInfo.getList());
        pageResult.setTotalPage(pageInfo.getPages());
        return pageResult;
    }

    @Override
    public Integer insertItemParam(Integer itemCatId, String paramData) {
       TbItemParamExample example=new TbItemParamExample();
        TbItemParamExample.Criteria criteria = example.createCriteria();
        criteria.andItemCatIdEqualTo(Long.valueOf(itemCatId));
        List<TbItemParam> list=itemParamMapper.selectByExample(example);
        if (list.size()>0){
            return 0;
        }

        TbItemParam tbItemParam=new TbItemParam();
        tbItemParam.setParamData(paramData);
        tbItemParam.setItemCatId(Long.valueOf(itemCatId));
        tbItemParam.setCreated(new Date());
        tbItemParam.setUpdated(new Date());

        Integer num=itemParamMapper.insertSelective(tbItemParam);

        return num;
    }

    @Override
    public Integer deleteItemParamById(Integer id) {
        Integer num = itemParamMapper.deleteByPrimaryKey(Long.valueOf(id));

        return num;
    }

    /**
     * 查询首页商品分类
     * @return
     */
    @Override
    public CatResult selectItemCategoryAll() {
      CatResult catResult=new CatResult();
        //查询缓存
        CatResult catResultRedis =
                (CatResult)redisClient.get(PROTAL_CATRESULT_KEY);
        if(catResultRedis!=null){
            return catResultRedis;
        }

      catResult.setData(getCatList(0L));
        //添加到缓存
        redisClient.set(PROTAL_CATRESULT_KEY,catResult);
        return catResult;
    }

    /**
     * 查询商品介绍
     * @param itemId
     * @return
     */
    @Override
    public TbItemDesc selectItemDescByItemId(Long itemId) {
        //查询缓存
        TbItemDesc tbItemDesc = (TbItemDesc) redisClient.get(
                ITEM_INFO + ":" + itemId + ":"+ DESC);
        if(tbItemDesc!=null){
            return tbItemDesc;
        }

        TbItemDescExample example=new TbItemDescExample();
        TbItemDescExample.Criteria criteria = example.createCriteria();
        criteria.andItemIdEqualTo(itemId);
        List<TbItemDesc> tbItemDescs = tbItemDescMapper.selectByExampleWithBLOBs(example);
        if (tbItemDescs!=null){
            //把数据保存到缓存
            redisClient.set(ITEM_INFO + ":" + itemId + ":"+ DESC,tbItemDescs.get(0));
            //设置缓存的有效期
            redisClient.expire(ITEM_INFO + ":" + itemId + ":"+ DESC,ITEM_INFO_EXPIRE);
            return tbItemDescs.get(0);
        }
        return null;
    }

    /**
     * 根据商品 ID 查询商品描述
     */
    @Override
    public TbItemParamItem selectTbItemParamItemByItemId(Long itemId) {
        //查询缓存
        TbItemParamItem tbItemParamItem = (TbItemParamItem) redisClient.get(
                ITEM_INFO + ":" + itemId + ":"+ PARAM);
        if(tbItemParamItem!=null){
            return tbItemParamItem;
        }

        TbItemParamItemExample example = new TbItemParamItemExample();
        TbItemParamItemExample.Criteria criteria = example.createCriteria();
        criteria.andItemIdEqualTo(itemId);
        List<TbItemParamItem> tbItemParamItemList =
                tbItemParamItemMapper.selectByExampleWithBLOBs(example);
        if(tbItemParamItemList!=null){
            //把数据保存到缓存
            redisClient.set(ITEM_INFO + ":" + itemId + ":"+
                    PARAM,tbItemParamItemList.get(0));
            //设置缓存的有效期
            redisClient.expire(ITEM_INFO + ":" + itemId + ":"+ PARAM,ITEM_INFO_EXPIRE);
            return tbItemParamItemList.get(0);
        }
        return null;

    }

    /**
     * 私有方法，查询商品分类
     */
    private List<?> getCatList(long parentId) {
        //创建查询条件
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbItemCat> list = tbItemCatMapper.selectByExample(example);

        List list1=new ArrayList();
        int count=0;
        for (TbItemCat tbItemCat:list){
            //判断是否是父节点
            if (tbItemCat.getIsParent()){
                CatNode catNode = new CatNode();
                catNode.setName(tbItemCat.getName());
                catNode.setItem(getCatList(tbItemCat.getId()));
                list1.add(catNode);
                count ++;
                if (count == 18){
                    break;
                }
            }else{
                list1.add(tbItemCat.getName());
            }
        }
        return list1;
    }


}
